﻿# coding:utf-8
import json
import datetime
import time
from datetime import datetime, timedelta
import os
from flask import Blueprint, render_template, request, jsonify, redirect, g, current_app, url_for
from sqlalchemy import or_
from sqlalchemy import text
from werkzeug.utils import secure_filename
from web.utils import  excel
from web.forms import SigninForm, AdminloginForm
from web.forms.site import SiteInfo, ProductInfo, ModalTypeInfo, TouguProductInfo, AlipayInfo, ZhuzibaoInfo
from web.models import db, Alipay, PayLog
from web.models.product import Product, TouguProduct, ModalType, TouguProductData, Zhuzibao
from web.models.site import Site
from ..models.user import User

from ..utils.account import signin_user, signout_user
from ..utils.permissions import require_admin, ADMIN_PSW, ADMIN_EMAIL

bp = Blueprint("admin", __name__)

"""
首先需要登录管理员账号：
admin@tuomeng.com tuomeng2014
写在permissions.py里面了
"""


@bp.route("/", methods=('GET', 'POST'))
@bp.route("/login", methods=('GET', 'POST'))
def login():
    form = AdminloginForm()
    status = ""
    if g.user:
        return redirect("admin/home")
    if request.method == 'POST':
        if form.is_submitted():

            user = User.query.filter(User.name == form.admin_name.data).first()
            if user.check_password(form.password.data):
                signin_user(user)
                return redirect("admin/home")
            else:
                print "error username or password"
        else:
            status = "登录失败"
            print "error"
    return render_template("admin/login.html", form=form, status=status)


@bp.route("/home", methods=('GET', 'POST'))
@require_admin
def home():
    return render_template("admin/home.html")


@bp.route("/site_info", methods=('GET', 'POST'))
@require_admin
def site_info():
    form = SiteInfo()
    info = Site.query.first()
    if request.method == 'POST':
        if not info:
            info = Site(url=form.url.data, name=form.name.data, sitelogo=form.logo.data, desc=form.desc.data,
                        title=form.title.data)
            db.session.add(info)
        else:
            info.url = form.url.data
            info.name = form.name.data
            info.title = form.title.data
            info.sitelogo = form.logo.data
            info.desc = form.desc.data
        db.session.commit()
    else:
        if info:
            form.url.data = info.url
            form.name.data = info.name
            form.title.data = info.title
            form.logo.data = info.sitelogo
            form.desc.data = info.desc
    return render_template("admin/site_info.html", form=form, admin_nav=1, info=info)


@bp.route("/alipay_info", methods=('GET', 'POST'))
@require_admin
def alipay_info():
    form = AlipayInfo()
    info = Site.query.first()
    if request.method == 'POST':
        if not info:
            info = Alipay(email=form.email.data, pid=form.pid.data,
                          key=form.key.data)
            db.session.add(info)
        else:
            info.email = form.email.data
            info.pid = form.pid.data
            info.key = form.key.data

        db.session.commit()
    else:
        if info:
            form.email.data = info.email
            form.pid.data = info.pid
            form.key.data = info.key
    return render_template("admin/alipay_info.html", form=form, admin_nav=1, info=info)


@bp.route("/userlist", methods=('GET', 'POST'))
@require_admin
def userlist():
    users = User.query.all()
    return render_template("admin/users.html", users=users)


@bp.route("/modal_list", methods=('GET', 'POST'))
@require_admin
def modal_list():
    modal_types = ModalType.query.all()
    return render_template("admin/modal_list.html", admin_nav=3, modal_types=modal_types)


@bp.route("/modal_type/setting", methods=('GET', 'POST'))
@require_admin
def modal_type_setting():
    form = ModalTypeInfo()
    id = int(request.args.get("id", 0))
    info = ModalType.query.get(id)
    if request.method == 'POST':
        if not info:
            info = ModalType(name=form.name.data)

        else:
            info.name = form.name.data
        db.session.add(info)
        db.session.commit()
        return redirect(url_for('admin.modal_list'))
    else:
        if info:
            form.name.data = info.name
    return render_template("admin/modal_type_setting.html", form=form, admin_nav=3, info=info)


@bp.route("/add_tougu_product", methods=('GET', 'POST'))
@require_admin
def tougu_product_setting():
    form = TouguProductInfo()
    modal_types = ModalType.query.all()
    id = int(request.args.get("id", 0))
    info = TouguProduct.query.get(id)
    if request.method == 'POST':
        if not info:
            info = TouguProduct(name=form.name.data, modal_id=int(form.type_id.data))

        else:
            info.name = form.name.data
        db.session.add(info)
        db.session.commit()
        return redirect(url_for('admin.tougu_product_list'))
    else:
        if info:
            form.name.data = info.name
            form.type_id.data = info.modal_id

        else:
            info = {}
    return render_template("admin/tougu_product_setting.html", admin_nav=3, form=form, modal_types=modal_types,
                           info=info)


@bp.route("/tougu_product_upload_data", methods=('GET', 'POST'))
@require_admin
def tougu_product_upload_data():
    form = TouguProductInfo()
    modal_types = ModalType.query.all()
    id = int(request.args.get("id", 0))
    modal_info = TouguProduct.query.get(id)
    if request.method == 'POST':
        #一周内的数据
        info = TouguProductData.query.filter(text("week(create_time)=week(now())")).all()
        base_dir=current_app.config['EXCEL_PATH']
        filename=excel.getLastExcelFile(base_dir)
        infos= excel.getAllRowsBySheetIndex(0,os.path.join(base_dir,filename))
    #名称，周盈利,产品编号，全部名称，分类，品种，平台，周期，适用合约，最大回撤，胜算率，年度收益率，每次盈利，已订购，已跟踪，上线时间，评定
        if info is None:##添加
            for i in range(2,len(infos)):
                if infos[i][1]=='':
                    break
                info=TouguProductData(product_id=infos[i][5],excel_file=filename,week_income=infos[i][3],code=infos[i][5],full_name=infos[i][6].decode('utf-8'),
                                      type=infos[i][7].decode('utf-8'),variety=infos[i][8].decode('utf-8'),platform=infos[i][9].decode('utf-8'),
                                      cycle=infos[i][10].decode('utf-8'),contract=infos[i][11].decode('utf-8'),
                                      max_return=infos[i][12],win_odds=infos[i][13],year_income=infos[i][14],once_average_lost=infos[i][15],once_average_income=infos[i][16],
                                      month_income=infos[i][17],is_ordered=infos[i][18].decode('utf-8'),is_followed=infos[i][19].decode('utf-8'),
                                      online_time= datetime.datetime.strptime(infos[i][20],'%Y-%m-%d %X'),desc=infos[i][21].decode('utf-8'),create_time= time.strftime('%Y-%m-%d %X',time.localtime()))
                db.session.add(info)
        else:##覆盖
            for i in range(0,len(info)):
                db.session.delete(info[i])
            for i in range(2,len(infos)):
                if infos[i][1]=='':
                    break
                info=TouguProductData(product_id=infos[i][5],excel_file=filename,week_income=infos[i][3],code=infos[i][5],full_name=infos[i][6].decode('utf-8'),
                                      type=infos[i][7].decode('utf-8'),variety=infos[i][8].decode('utf-8'),platform=infos[i][9].decode('utf-8'),
                                      cycle=infos[i][10].decode('utf-8'),contract=infos[i][11].decode('utf-8'),
                                      max_return=infos[i][12],win_odds=infos[i][13],year_income=infos[i][14],once_average_lost=infos[i][15],once_average_income=infos[i][16],
                                      month_income=infos[i][17],is_ordered=infos[i][18].decode('utf-8'),is_followed=infos[i][19].decode('utf-8'),
                                      online_time=infos[i][20],desc=infos[i][21].decode('utf-8'),create_time= time.strftime('%Y-%m-%d %X',time.localtime()))
                db.session.add(info)
        db.session.commit()
        return redirect(url_for('admin.tougu_product_list'))
    else:
        info = TouguProductData.query.filter(TouguProductData.product_id == id,text("week(create_time)=week(now())")).first()
        if info:
            form.type_id.data = modal_info.id
            form.excel_file.data = info.excel_file

        else:
            info = {}
    return render_template("admin/tougu_product_upload_data.html", admin_nav=3, form=form, modal_info=modal_info,
                           modal_types=modal_types,
                           info=info)


@bp.route("/tougu_product_list", methods=('GET', 'POST'))
@require_admin
def tougu_product_list():
    products = TouguProduct.query.all()
    return render_template("admin/tougu_product_list.html", admin_nav=3, products=products)


@bp.route("/add_product", methods=('GET', 'POST'))
@require_admin
def product_setting():
    form = ProductInfo()
    id = int(request.args.get("id", 0))
    info = Product.query.get(id)
    if request.method == 'POST':
        if not info:
            info = Product(name=form.name.data, image=form.image.data,
                           year_income=form.year_income.data, win_odds=form.win_odds.data,
                           month_income=form.month_income.data, max_return=form.max_return.data,
                           once_average_income=form.once_average_income.data,
                           once_average_lost=form.once_average_lost.data, url=form.url.data)

        else:
            info.name = form.name.data
            info.image = form.image.data
            info.win_odds = form.win_odds.data
            info.year_income = form.year_income.data
            info.month_income = form.month_income.data
            info.max_return = form.max_return.data
            info.once_average_income = form.once_average_income.data
            info.once_average_lost = form.once_average_lost.data
            info.url = form.url.data
        db.session.add(info)
        db.session.commit()
        return redirect(url_for('admin.product_list'))
    else:
        if info:
            form.name.data = info.name
            form.image.data = info.image
            form.win_odds.data = info.win_odds
            form.year_income.data = info.year_income
            form.month_income.data = info.month_income
            form.max_return.data = info.max_return
            form.once_average_income.data = info.once_average_income
            form.once_average_lost.data = info.once_average_lost
            form.url.data = info.url
        else:
            info = {}
    return render_template("admin/product_setting.html", admin_nav=4, form=form, info=info)


@bp.route("/product_list", methods=('GET', 'POST'))
@require_admin
def product_list():
    products = Product.query.all()
    return render_template("admin/product_list.html", admin_nav=4, products=products)


@bp.route("/zhuzibao", methods=('GET', 'POST'))
@require_admin
def zhuzibao():
    form = ZhuzibaoInfo()
    info = Zhuzibao.query.first()
    if request.method == 'POST':
        if not info:
            info = Zhuzibao(image=form.image.data, price1=form.price1.data, price2=form.price2.data,
                            price3=form.price3.data,desc=form.desc.data)

        else:
            info.image = form.image.data
            info.price1 = form.price1.data
            info.price2 = form.price2.data
            info.price3 = form.price3.data
            info.desc = form.desc.data
        db.session.add(info)
        db.session.commit()
    else:
        if info:
            form.image.data = info.image
            form.price1.data = info.price1
            form.price2.data = info.price2
            form.price3.data = info.price3
            form.desc.data = info.desc
        else:
            info = {}
    return render_template("admin/zhuzibao.html", admin_nav=5,form=form)


@bp.route("/orders", methods=('GET', 'POST'))
@require_admin
def orders():
    type = request.args.get("type")
    if type == 'paid':
        orders = PayLog.query.filter(
            or_(PayLog.trade_status == 'TRADE_SUCCESS', PayLog.trade_status == 'TRADE_FINISHED'))
    else:
        orders = PayLog.query.filter(PayLog.trade_status == None)
    return render_template("admin/orders.html", admin_nav=6, orders=orders)


@bp.route("/tougu_product/delete", methods=('GET', 'POST'))
@require_admin
def delete_tougu():
    datas = request.form
    for key, value in datas.items():
        product = TouguProduct.query.get(int(value[0]))
        db.session.delete(product)
        db.session.commit()
    return json.dumps({"status": 'ok'})


@bp.route("/product/delete", methods=('GET', 'POST'))
@require_admin
def delete_product():
    datas = request.form
    for key, value in datas.items():
        product = Product.query.get(int(value[0]))
        db.session.delete(product)
        db.session.commit()
    return json.dumps({"status": 'ok'})

@bp.route("/upload_excel", methods=('GET', 'POST'))
@require_admin
def upload_excel():
    UPLOAD_FOLDER = current_app.config['EXCEL_PATH']
    print UPLOAD_FOLDER
    if request.method == 'POST':
        f = request.files['file']
        fname = secure_filename(f.filename)  # 获取一个安全的文件名，且仅仅支持ascii字符；
        # fname = random_str() + ".pdf"
        path = os.path.join(UPLOAD_FOLDER, fname)
        f.save(path)
        return (json.dumps({"status": 'ok', "msg": "", "base_url": "", "name": fname}))


@bp.route('/loginout')
def loginout():
    """登出"""
    signout_user()
    return redirect(url_for('admin.login'))
